<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="600">
    <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules"
             label-width="100px">
      <el-form-item label="设备厂商" prop="supplierId">
        <el-select v-model="formData.supplierId" placeholder="请选择设备厂商"
                   @change="supplierChange" style="width: 300px;">
          <el-option v-for="item in suppliers" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item v-if="formData.supplierId !== 3" label="门禁设备" prop="deviceId">
        <el-select v-model="formData.deviceId" placeholder="请选择门禁设备" filterable
                   @change="deviceChange" style="width: 300px;">
          <el-option v-for="item in devices" :key="item.code" :label="item.name"
                     :value="item.code"/>
        </el-select>
      </el-form-item>
      <el-form-item v-if="formData.supplierId === 3" label="门禁设备" prop="logicId">
        <el-select v-model="formData.logicId" placeholder="请选择门禁设备" filterable
                   @change="deviceChange" style="width: 300px;">
          <el-option v-for="item in devices" :key="item.code" :label="item.name"
                     :value="item.code"/>
        </el-select>
      </el-form-item>
      <el-form-item label="蓝牙设备" prop="blueToothDeviceId" v-if="isBlueTooth">
        <el-select v-model="formData.blueToothLogicId" placeholder="请选择蓝牙门禁设备" filterable
                   @change="blueToothDeviceChange" style="width: 300px;">
          <el-option v-for="item in blueToothDevices" :key="item.code" :label="item.name"
                     :value="item.code"/>
        </el-select>
      </el-form-item>

      <!-- XYA -->
      <el-form-item v-if="formData.supplierId === 2" label="蓝牙设备名称" prop="blueToothName">
        <el-input v-model="formData.blueToothName" placeholder="请输入蓝牙设备名称" @input="handleBlueToothNameChange" clearable/>
      </el-form-item>
      <el-form-item v-if="formData.supplierId === 2" label="蓝牙mac地址" prop="blueToothMac">
        <el-input v-model="formData.blueToothMac" placeholder="请输入蓝牙设备mac" clearable/>
      </el-form-item>
<!--      <el-form-item v-if="formData.supplierId === 2" label="蓝牙开锁秘钥" prop="blueToothOpenPassword">-->
<!--        <el-input v-model="formData.blueToothOpenPassword" placeholder="请输入蓝牙设备名称" clearable maxlength="20"/>-->
<!--      </el-form-item>-->

      <el-form-item label="设备名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入设备名称" clearable maxlength="20"/>
      </el-form-item>
      <el-form-item label="管理员手机号" prop="mobile">
        <el-input v-model="formData.mobile" placeholder="请输入手机号" clearable maxlength="20"/>
      </el-form-item>
      <el-form-item label="设备状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio v-for="dict in getIntDictOptions(DICT_TYPE.YXT_EQUIPMENT_STATUS)"
                    :key="dict.value" :label="dict.value">
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import {useMessage} from "@/components/Notice";
import {useEquipmentApi, useSupplierApi} from "@/api/yxt/supplier";
import {ReverseStatusEnum} from "@/utils/constants";
import {DICT_TYPE, getIntDictOptions} from "@/utils/dict";

defineOptions({name: 'YxtEquipmentForm'})

const {t} = useI18n()
const supplierApi = useSupplierApi();
const equipmentApi = useEquipmentApi();

const isBlueTooth = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
const formData = ref({
  id: undefined,
  name: '',
  blueToothName: '',
  supplierId: undefined,
  deviceId: '',
  blueToothDeviceId: '',
  blueToothOpenPassword:'',
  blueToothBattery: undefined,
  hardwareId: '',
  mobile: '',
  status: ReverseStatusEnum.ENABLE,
  blutToothLogicId: ''
})

const validateDevice = (rule, value, callback) => {
  console.log("----" + formData.value.blueToothLogicId)
  if (formData.value.supplierId ==3 && !formData.value.deviceId && !formData.value.blueToothLogicId && !formData.value.logicId) {
    callback(new Error('门禁设备和蓝牙设备至少选择一个'));
  } else {
    callback();
  }
};

const formRules = reactive({
  supplierId: [{required: true, message: '设备厂商不能为空', trigger: ['blur', 'change']}],
  deviceId: [
    {validator: validateDevice, trigger: 'change'}
  ],
  logicId: [
    {validator: validateDevice, trigger: 'change'}
  ],
  blueToothLogicId: [
    {validator: validateDevice, trigger: 'change'}
  ]

})

const formRef = ref<any>()
const suppliers = ref<Array<any>>([])
const devices = ref<Array<any>>([])
const blueToothDevices = ref<Array<any>>([])

const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  if (id) {
    formLoading.value = true
    try {
      formData.value = await equipmentApi.getObj(id)
      if (formData.value.supplierId === 3) {
        isBlueTooth.value = true;
      }
      await getDevices(id, formData.value.supplierId);
      await getBlueToothDevices(id, formData.value.supplierId);
    } finally {
      formLoading.value = false
    }
  }
  suppliers.value = await supplierApi.getSimpleList();
}
defineExpose({open})

const emit = defineEmits(['success'])
const submitForm = () => {
  formRef.value?.validate(async (valid: any) => {
    if (valid) {
      formLoading.value = true
      try {
        const data = formData.value
        if (formType.value === 'create') {
          await equipmentApi.createObj(data);
          useMessage(t('common.createSuccess'));
        } else {
          await equipmentApi.updateObj(data);
          useMessage(t('common.updateSuccess'));
        }
        dialogVisible.value = false
        emit('success')
      } finally {
        formLoading.value = false
      }
    }
  });
}

const resetForm = () => {
  devices.value = [];
  formData.value = {
    id: undefined,
    name: '',
    supplierId: undefined,
    deviceId: '',
    hardwareId: '',
    mobile: '',
    status: ReverseStatusEnum.ENABLE,
    blueToothMac: '',
    blueToothName: '',
    blueToothOpenPassword:'',
    logicId: '',
    nodeId: undefined,
    battery: undefined,
    blueToothBattery: undefined
  }
  formRef.value?.resetFields()
  isBlueTooth.value = false;
}

async function supplierChange(supplierId: any) {
  isBlueTooth.value = supplierId == 3;
  formData.value.deviceId = '';
  formData.value.hardwareId = '';
  await getDevices(formData.value.id, supplierId).catch(() => {
    devices.value = [];
  });
  if (supplierId == 3) {
    await getBlueToothDevices(formData.value.id, supplierId).catch(() => {
      blueToothDevices.value = [];
    })
  }
}

// 蓝牙设备名称变化
const handleBlueToothNameChange = () => {
// 提取 BLE_MAC，蓝牙设备 mac 地址（从第 5 到第 10 字节，即第 8 到 20 个字符）
  let bleMac = formData.value.blueToothName.substring(8, 20);

  // 将一个字符串的每两位添加冒号分隔，将其格式化为以冒号分隔的十六进制字符串
  let formattedMac = '';
  for (let i = 0; i < bleMac.length; i += 2) {
    if (i > 0) formattedMac += ":";
    // 在每两个字符之间添加冒号
    formattedMac += bleMac.substring(i, i + 2);
  }

  // 转换为大写字母
  bleMac = formattedMac.toUpperCase();

  formData.value.blueToothMac = bleMac;
}

async function deviceChange(val: any) {
  const find = devices.value.find(res => res.code == val)
  formData.value.hardwareId = find.hardwareId;
  if (formData.value.supplierId != 3) {
    formData.value.name = find.name;
  }
  formData.value.battery = find.battery;
  formData.value.logicId = find.logicId;
  formData.value.nodeId = find.nodeId;
}

async function blueToothDeviceChange(val: any) {
  const find = blueToothDevices.value.find(res => res.logicId == val);
  formData.value.blueToothMac = find.blueToothMac;
  formData.value.blueToothName = find.blueToothName;
  // formData.value.name = find.blueToothName;
  formData.value.blueToothLogicId = find.logicId;
  formData.value.blueToothNodeId = find.nodeId;
}

async function getDevices(id: any, supplierId: any) {
  devices.value = await supplierApi.getEquipmentList({
    id: id,
    supplierId: supplierId,
    update: formType.value == 'update'
  });
}

async function getBlueToothDevices(id: any, supplierId: any) {
  blueToothDevices.value = await supplierApi.getEquipmentList({
    id: id,
    supplierId: supplierId,
    update: formType.value == 'update',
    isBlueTooth: true
  });
}

// const deviceName = computed({
//   get: () => {
//     // 初次选择蓝牙设备时填充蓝牙名称，后续手动修改时不再覆盖
//     return formData.value.name || formData.value.blueToothName || '';
//   },
//   set: (value) => {
//     console.log("设置名称：" + value);
//     formData.value.name = value;
//   }
// });
//
// // 监听 blueToothDeviceId 的变化来自动填充设备名称
// watch(() => formData.value.blueToothDeviceId, (newVal) => {
//   if (newVal) {
//     // 如果蓝牙设备 ID 存在，且设备名称尚未被手动修改，使用蓝牙设备名称填充
//     formData.value.name = formData.value.blueToothName || formData.value.name;
//   }
// });


</script>
